package com.baizhi.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 创建MyBatis相关的Bean
 */

public class MyBatisConfig {

    //创建SQLSessionFactoryBean
    @Bean
    public SqlSessionFactoryBean createSqlSessionFactoryBean(DataSource dataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        //设置别名
        sqlSessionFactoryBean.setTypeAliasesPackage("com.baizhi.pojo");
        return sqlSessionFactoryBean;
    }

    //Mapper接口扫描的Bean
    @Bean
    public MapperScannerConfigurer createMapperScannerConfigurer(){
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        //设置Mapper接口的位置
        mapperScannerConfigurer.setBasePackage("com.baizhi.mapper");
        return mapperScannerConfigurer;
    }

    //事务管理的Bean
    /**
     *    <!--配置事务管理器-->
     *     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
     *         <property name="dataSource" ref="dataSource"/>
     *     </bean>
     */
    @Bean
    public DataSourceTransactionManager createDataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }
}
